package ru.spbau.database.group3.queryEvaluator;

import ru.spbau.database.group3.engine.Column;
import ru.spbau.database.group3.engine.DatabaseEngine;
import ru.spbau.database.group3.types.Type;
import ru.spbau.database.group3.types.Types;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: stas
 * Date: 1/29/13
 * Time: 2:07 PM
 */
public class CreateTableInstruction implements Instruction {

    public CreateTableInstruction(String tableName, List<String> types, List<String> names) {
        if(types.size() != names.size()) {
            throw new IllegalArgumentException("Types and Names must have the same size!");
        }
        this.tableName = tableName;
        this.columns = createColumns(names, types);
    }

    @Override
    public QueryResult handle(DatabaseEngine engine) throws IOException, ClassNotFoundException {
        return engine.createTable(tableName, columns);
    }

    private List<Column> createColumns(List<String> names, List<String> types) {
        List<Column> columns = new ArrayList<Column>();
        int offset = 0;
        for(int i = 0; i < names.size(); ++i) {
            Type type = Types.parseString(types.get(i)).forName(types.get(i));
            columns.add(new Column(names.get(i), offset, type));
            offset += type.size();
        }
        return columns;
    }

    private String tableName;
    private List<Column> columns;
}
